package com.yunkaweilai.android.activity.operation.integral;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.model.Event;
import com.yunkaweilai.android.model.integral.IntegralGoodListModel;
import com.yunkaweilai.android.model.integral.IntegralSearchModel;
import com.yunkaweilai.android.model.integral.IntegralShopListModel;
import com.yunkaweilai.android.model.integral.IntegralTypeListModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.InputMethodUtils;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;


/**
 * 礼品设置界面
 */
public class IntegralSettingActivity extends BaseActivity implements BGARefreshLayout.BGARefreshLayoutDelegate {

    @BindView(R.id.id_edt_search)
    EditText idEdtSearch;
    @BindView(R.id.id_img_clean)
    ImageView idImgClean;
    @BindView(R.id.id_listView_left)
    ListView idListViewLeft;
    @BindView(R.id.id_listView_right)
    ListView idListViewRight;
    @BindView(R.id.id_shop_llayout)
    LinearLayout idShopLlayout;
    @BindView(R.id.id_listView_search)
    ListView idListViewSearch;
    @BindView(R.id.id_search_rllayout)
    RelativeLayout idSearchRllayout;
    @BindView(R.id.content_view)
    FrameLayout contentView;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    @BindView(R.id.id_multipleStatusView1)
    MultipleStatusView idMultipleStatusView1;
    @BindView(R.id.id_refresh)
    BGARefreshLayout idRefresh;
    private String gift_category_id = "0";
    private Gson gson = new Gson();
    private int mpage = 1;
    private boolean mHasMore = true;
    private Map<String, IntegralGoodListModel> shopMap = new HashMap<>();
    private ArrayList<IntegralTypeListModel.DataBean.ListBean> typeList = new ArrayList<>();
    private CommonAdapter<IntegralTypeListModel.DataBean.ListBean> typeAdapter;
    private ArrayList<IntegralGoodListModel> shopList = new ArrayList<>();
    private CommonAdapter<IntegralGoodListModel> shopAdapter;
    private String keywords = "";
    private CommonAdapter<IntegralGoodListModel> searchAdapter;
    private ArrayList<IntegralGoodListModel> searchList = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_integral_setting);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        new TitleBuilder(mAc).setTitleText("礼品设置").setLeftImage(R.mipmap.ic_go_back)
                .setLeftOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if ("".equals(idEdtSearch.getText().toString())) {
                            finish();
                        } else {
                            idImgClean.setVisibility(View.GONE);
                            idEdtSearch.setText("");
                        }
                    }
                }).setRightText("新增礼品").setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                intent2Activity(AddIntegralActivity.class);
            }
        });
        ButterKnife.bind(this);
        initRefreshLayout(idRefresh, this, true);
        idMultipleStatusView.showLoading();
        idMultipleStatusView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initHttp();
            }
        });
        idMultipleStatusView1.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initShopListHttp(true);
            }
        });


        initAdapter();
        initClick();
        initHttp();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onShopEvent(Event.TypeEvent event) {
        if (event != null) {
            if (event.type == CommonConstants.SHOP_LIST_REFRESH) {
                if (event.flag) {
                    initHttp();
                }
            }
        }
    }

    private void initClick() {
        idEdtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if ((actionId == 0 || actionId == 3) && event != null && idEdtSearch.length() > 0) {
                    //点击搜索要做的操作
                    keywords = idEdtSearch.getText().toString();
                    InputMethodUtils.closeSoftKeyboard(mAc);
                    initSearch();
                }
                return false;
            }
        });

        idEdtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s == null || s.length() == 0) {
                    idImgClean.setVisibility(View.GONE);
                    idSearchRllayout.setVisibility(View.GONE);
                    idShopLlayout.setVisibility(View.VISIBLE);
                    return;
                } else {
                    idImgClean.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        idListViewLeft.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                gift_category_id = typeList.get(i).getGift_category_id();
                idRefresh.beginRefreshing();
                initShopListHttp(true);
                for (int j = 0; j < typeList.size(); j++) {
                    IntegralTypeListModel.DataBean.ListBean listBean = typeList.get(j);
                    if (j == i) {
                        listBean.setCheck(true);
                    } else {
                        listBean.setCheck(false);
                    }
                }
                typeAdapter.notifyDataSetChanged();
            }
        });


        idImgClean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                idImgClean.setVisibility(View.GONE);
                idEdtSearch.setText("");
            }
        });

        idListViewRight.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                IntegralShopActivity.actionStart(mAc, shopList.get(i).getId());
            }
        });
        idListViewSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                IntegralShopActivity.actionStart(mAc, searchList.get(i).getId());
            }
        });
    }

    private void initAdapter() {
        typeAdapter = new CommonAdapter<IntegralTypeListModel.DataBean.ListBean>(mAc, R.layout.item_list_left, typeList) {
            @Override
            protected void convert(ViewHolder viewHolder, IntegralTypeListModel.DataBean.ListBean item, int position) {
                viewHolder.setText(R.id.id_textView, item.getGift_category_name() + "");
                TextView idTvBuyNum = viewHolder.getView(R.id.id_tv_buy_num);

                TextView idTv = viewHolder.getView(R.id.id_textView);
                RelativeLayout rlayout = viewHolder.getView(R.id.id_rlayout_all);
                if (item.isCheck()) {
                    rlayout.setBackgroundColor(getResources().getColor(R.color.bg_white));
                    idTv.setTextColor(getResources().getColor(R.color.wjx_content_txt));
                    TextPaint tp = idTv.getPaint();
                    tp.setFakeBoldText(true);//选中加粗
                } else {
                    rlayout.setBackgroundColor(getResources().getColor(R.color.wjx_type_list_bg));
                    idTv.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_right));
                    TextPaint tp = idTv.getPaint();
                    tp.setFakeBoldText(false);//选中加粗
                }
                int num = 0;
                for (String key : shopMap.keySet()) {
                    IntegralGoodListModel listBean = shopMap.get(key);
                    if (listBean.getCategory_id().equals(item.getGift_category_id())) {
                        num += listBean.getBuy_num();
                    }
                }
                if (num > 0) {
                    idTvBuyNum.setVisibility(View.VISIBLE);
                    idTvBuyNum.setText(num + "");
                } else {
                    idTvBuyNum.setVisibility(View.GONE);
                    idTvBuyNum.setText("0");
                }
            }
        };
        shopAdapter = new CommonAdapter<IntegralGoodListModel>(mAc, R.layout.item_list_shop_consumption, shopList) {
            @Override
            protected void convert(ViewHolder viewHolder, final IntegralGoodListModel item, int position) {
                viewHolder.setVisible(R.id.id_tv_tingyong, false);
                viewHolder.setText(R.id.id_tv_tingyong, "停用中");
                ImageView mIdImg = viewHolder.getView(R.id.id_img);
                Utils.shopInfoImg(mAc, item.getGift_image(), mIdImg);
//                mIdImg.setVisibility(View.GONE);
                viewHolder.setText(R.id.id_tv_name, item.getGift_name() + "");
                viewHolder.setText(R.id.id_tv_price, item.getPoints_price() + "");
                viewHolder.setText(R.id.id_tv_unit, "/积分");
//                viewHolder.setText(R.id.id_tv_info, "编号：" + item.getGift_sku() + " 库存：" + item.getGift_stock());
                viewHolder.setText(R.id.id_tv_info, "库存：" + item.getGift_stock());
                viewHolder.setVisible(R.id.id_img_add, false);
                if (item.getStatus().equals("0")) {
                    viewHolder.setVisible(R.id.id_tv_tingyong, true);
                } else if (item.getIs_expired() == 0) {
                    viewHolder.setVisible(R.id.id_tv_tingyong, true);
                    viewHolder.setText(R.id.id_tv_tingyong, "已过期");
                }
            }
        };
        idListViewLeft.setAdapter(typeAdapter);
        idListViewRight.setAdapter(shopAdapter);

        searchAdapter = new CommonAdapter<IntegralGoodListModel>(mAc, R.layout.item_list_shop_consumption, searchList) {
            @Override
            protected void convert(ViewHolder viewHolder, final IntegralGoodListModel item, int position) {
                viewHolder.setVisible(R.id.id_tv_tingyong, false);
                viewHolder.setText(R.id.id_tv_tingyong, "停用中");
                ImageView mIdImg = viewHolder.getView(R.id.id_img);
                Utils.shopInfoImg(mAc, item.getGift_image(), mIdImg);
//                mIdImg.setVisibility(View.GONE);
                viewHolder.setText(R.id.id_tv_name, item.getGift_name() + "");
                viewHolder.setText(R.id.id_tv_price, item.getPoints_price() + "");
                viewHolder.setText(R.id.id_tv_unit, "/积分");
//                viewHolder.setText(R.id.id_tv_info, "编号：" + item.getGift_sku() + " 库存：" + item.getGift_stock());
                viewHolder.setText(R.id.id_tv_info, "库存：" + item.getGift_stock());
                viewHolder.setVisible(R.id.id_img_add, false);
                if (item.getStatus().equals("0")) {
                    viewHolder.setVisible(R.id.id_tv_tingyong, true);
                } else if (item.getIs_expired() == 0) {
                    viewHolder.setVisible(R.id.id_tv_tingyong, true);
                    viewHolder.setText(R.id.id_tv_tingyong, "已过期");
                }
            }
        };
        idListViewSearch.setAdapter(searchAdapter);
    }


    private void initSearch() {
        HttpRequest.postUrl(Api.APP_INTEGRAL_SEARCH)
                .addParams("keyword", keywords)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        Gson gson = new Gson();
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            IntegralSearchModel searchModel = gson.fromJson(json, IntegralSearchModel.class);
                            searchList.clear();
                            searchList.addAll(searchModel.getData().getList());
                            searchAdapter.notifyDataSetChanged();
                            if (searchList.size() > 0) {
                                idShopLlayout.setVisibility(View.GONE);
                                idSearchRllayout.setVisibility(View.VISIBLE);
                            } else {
                                showToast("暂无此商品");
                            }

                        }
                    }

                    @Override
                    public void onError(Exception e) {

                    }
                });
    }


    //获取分类
    private void initHttp() {
        HttpRequest.postUrl(Api.APP_INTEGRAL_TYPE)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            IntegralTypeListModel integralTypeModel = gson.fromJson(json, IntegralTypeListModel.class);
                            typeList.clear();
                            typeList.addAll(integralTypeModel.getData().getList());
                            typeAdapter.notifyDataSetChanged();
                            if (typeList.size() > 0) {
                                typeList.get(0).setCheck(true);
                                gift_category_id = typeList.get(0).getGift_category_id();
                                initShopListHttp(true);
                            } else {
                                if (idMultipleStatusView != null) {
                                    idMultipleStatusView.showEmpty();
                                }
                            }
                        } else {
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showError();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showError();
                        }
                    }
                });

    }

    //获取商品列表
    private boolean initShopListHttp(boolean refresh) {
        mpage = refresh ? 1 : mpage;
        if ((!mHasMore) && (!refresh)) {
            endRefreshOrLoad(false);
            showToast("没有更多数据了");
            return false;
        }
        HttpRequest.postUrl(Api.CONSUME_FIGT_SHOP_CATEGORY)
                .addParams("ShowPage", "1")
                .addParams("PageSize", "10")
                .addParams("CurrPage", mpage + "")
                .addParams("gift_category_id", gift_category_id)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        endRefreshOrLoad(true);
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            IntegralShopListModel integralShopListModel = gson.fromJson(json, IntegralShopListModel.class);
                            shopList.clear();
                            shopList.addAll(integralShopListModel.getData().getList());
                            mHasMore = integralShopListModel.getData().getPage().isNext();//如果接收到完整10个数据，说明还有下一页
                            shopAdapter.notifyDataSetChanged();
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showContent();
                            }
                            if (idMultipleStatusView1 != null) {
                                idMultipleStatusView1.showContent();
                            }
                            if (shopList.isEmpty()) {
                                idMultipleStatusView1.showEmpty();
                            }
                        } else {
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showError();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        endRefreshOrLoad(true);
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showError();
                        }
                    }
                });


        return true;


    }

    /**
     * 结束刷新组件
     *
     * @param refresh
     */
    private void endRefreshOrLoad(boolean refresh) {
        if (refresh) {
            if (idRefresh != null) {
                idRefresh.endRefreshing();
            }
        } else {
            if (idRefresh != null) {
                idRefresh.endLoadingMore();
            }
        }
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        initShopListHttp(true);
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        return initShopListHttp(false);
    }


}
